package com.fengwk.support.proxy.http;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fengwk.support.proxy.http.annotation.HttpClient;
import com.fengwk.support.util.SpringBeanUtils;

public class HttpProxy implements InvocationHandler {
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		// 获取注解
		HttpClient httpClient = HttpProxyUtils.getHttpClientAnnotation(proxy);
		RequestMapping requestMapping = HttpProxyUtils.getRequestMappingByMethod(method);
		PostMapping postMapping = HttpProxyUtils.getPostMappingByMethod(method);
		GetMapping getMapping = HttpProxyUtils.getGetMappingByMethod(method);
		Map<Integer, PathVariable> indexPathVariableMap = HttpProxyUtils.getIndexPathVariableMapByMethod(method);
		Map<Integer, RequestParam> indexRequestParamMap = HttpProxyUtils.getIndexRequestParamMapByMethod(method);
		
		// 编码
		Request request = SpringBeanUtils.getBean(Encode.class).encode(
				httpClient, 
				requestMapping, 
				postMapping, 
				getMapping, 
				indexPathVariableMap, 
				indexRequestParamMap, 
				args);
		
		// 请求
		Response response = SpringBeanUtils.getBean(Connect.class).connect(requestMapping, postMapping, getMapping, request);
		
		// 解码
		return SpringBeanUtils.getBean(Decode.class).decode(httpClient, response, method.getReturnType());
		
	}

}
